﻿Imports System.IO

Public Class frmActions
    Private strRowFilter As String = String.Empty
    Private lActions As dsActionItem
    Private lFileName As String
    Private WithEvents lBindingSource As BindingSource

    Sub LoadData()
        Try
            If My.Settings.LastFile.Length <= 0 Then
                lFileName = "ActoionItems.xml"
            Else
                lFileName = My.Settings.LastFile
            End If
            lActions = New dsActionItem
            If File.Exists(lFileName) Then
                lActions.ReadXml(lFileName)
            End If
            My.Settings.LastFile = lFileName
            My.Settings.Save()
            Me.Text = "Meeting Mate " & lFileName
            For Each dr As dsActionItem.ActionItemsRow In lActions.ActionItems.Rows
                dr.StartDate = FormatDateTime(dr.StartDate, DateFormat.ShortDate)
                dr.ActionDate = FormatDateTime(dr.ActionDate, DateFormat.ShortDate)
            Next
        Catch ex As Exception
            BasicError(ex)
        End Try
    End Sub

    Sub SaveData()
        Try
            For Each dr As dsActionItem.ActionItemsRow In lActions.ActionItems.Rows
                dr.StartDate = FormatDateTime(dr.StartDate, DateFormat.ShortDate)
                dr.ActionDate = FormatDateTime(dr.ActionDate, DateFormat.ShortDate)
            Next
            lActions.WriteXml(lFileName)
            My.Settings.LastFile = lFileName
            My.Settings.Save()
        Catch ex As Exception
            BasicError(ex)
        End Try
    End Sub

    Private Sub frmActions_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ScreenSetUp()
        LoadData()
        BindingData()
    End Sub

    Sub ScreenSetUp()
        dgSummary.Dock = DockStyle.Fill
        pnlZoom.Visible = False
    End Sub

    Sub BasicError(ByVal pex As Exception)
        MessageBox.Show(pex.Message & vbCrLf & pex.StackTrace, "Error", MessageBoxButtons.OK)
    End Sub
#Region "Binding *******************************************************"

    Sub BindDatagrid()

        lBindingSource = New BindingSource
        lBindingSource.DataSource = lActions.ActionItems.DefaultView
        'lBindingSource.DataMember = lActions.ActionItems.TableName
        lBindingSource.MoveFirst()

        dgSummary.AutoGenerateColumns = False
        dgSummary.DataSource = lBindingSource

        Dim dcItemID As New DataGridViewTextBoxColumn
        With dcItemID
            .Name = "ItemID"
            .DataPropertyName = "ItemID"
            .HeaderText = "Item ID"
            .ReadOnly = True
            .Width = 20
            dgSummary.Columns.Add(dcItemID)
        End With

        Dim dcPrivacy As New DataGridViewComboBoxColumn
        With dcPrivacy
            .Name = "Privacy"
            .DataPropertyName = "Privacy"
            .HeaderText = "Privacy"
            .ReadOnly = False
            .DataSource = lActions.Privacy
            .DisplayMember = "Privacy"
            .ValueMember = "Privacy"
            dgSummary.Columns.Add(dcPrivacy)
        End With

        Dim dcStatus = New DataGridViewComboBoxColumn
        With dcStatus
            .Name = "Status"
            .DataPropertyName = "Status"
            .HeaderText = "Status"
            .ReadOnly = False
            .DataSource = lActions.Status
            .DisplayMember = "Status"
            .ValueMember = "Status"
            dgSummary.Columns.Add(dcStatus)
        End With

        Dim dcDescription = New DataGridViewTextBoxColumn
        With dcDescription
            .Name = "Description"
            .DataPropertyName = "Description"
            .HeaderText = "Description"
            .ReadOnly = False
            .Width = 300
            dgSummary.Columns.Add(dcDescription)
        End With

        Dim dcStartDate As New CalendarColumn()
        With dcStartDate
            .Name = "StartDate"
            .DataPropertyName = "StartDate"
            .HeaderText = "StartDate"
            .ReadOnly = False
            dgSummary.Columns.Add(dcStartDate)
        End With
        '
        Dim dcActionDate As New CalendarColumn()
        With dcActionDate
            .Name = "ActionDate"
            .DataPropertyName = "ActionDate"
            .HeaderText = "ActionDate"
            .ReadOnly = False
            dgSummary.Columns.Add(dcActionDate)
        End With

    End Sub

    Sub BindingData()
        Try
            BindDatagrid()

            txtDescription.DataBindings.Add(New Binding("Text", lBindingSource, "Description", True, DataSourceUpdateMode.OnValidation, String.Empty, String.Empty))
            lblItemID.DataBindings.Add(New Binding("Text", lBindingSource, "ItemID", True, DataSourceUpdateMode.OnValidation, String.Empty, String.Empty))
            '******************************************************************
            'Catagories
            Catagories.CheckOnClick = True

            Catagories.ParentValueMember = "ItemID"
            Catagories.ParentIDMember = "ItemID"

            Catagories.ChildValueMember = "CatagoryID"
            Catagories.ChildIDMember = "CatagoryID"
            Catagories.ChildDisplayMember = "Catagory"

            Catagories.ParentDataSource = lBindingSource
            Catagories.ChildDataSource = lActions.Catagories
            Catagories.RelationDataSource = lActions.Catagory_ActionItem

            filtCatagories.DataSource = lActions.Catagories
            filtCatagories.DisplayMember = "Catagory"
            filtCatagories.ValueMember = "CatagoryID"
            
            '******************************************************************
            'PersonAction
            PersonAction.CheckOnClick = True

            PersonAction.ParentValueMember = "ItemID"
            PersonAction.ParentIDMember = "ItemID"

            PersonAction.ChildValueMember = "PersonID"
            PersonAction.ChildIDMember = "PersonID"
            PersonAction.ChildDisplayMember = "Name"

            PersonAction.ParentDataSource = lBindingSource 'lActions.ActionItems
            PersonAction.ChildDataSource = lActions.Persons
            PersonAction.RelationDataSource = lActions.Person_ActionItem

            filtPeople.DataSource = lActions.Persons
            filtPeople.DisplayMember = "Name"
            filtPeople.ValueMember = "PersonID"

            

            txtCatagory.Tag = String.Empty
            txtPerson.Tag = String.Empty


        Catch ex As Exception
            BasicError(ex)
        End Try
    End Sub

#End Region

    Sub CreateNewFile()
        Try
            lActions = New dsActionItem
            Dim drPrivacy As dsActionItem.PrivacyRow
            For Each Str As String In My.Settings.Privacy.Split(";")
                If Str.Trim.Length > 0 Then
                    drPrivacy = lActions.Privacy.NewPrivacyRow
                    drPrivacy.Privacy = Str
                    lActions.Privacy.AddPrivacyRow(drPrivacy)
                End If
            Next

            Dim drStatus As dsActionItem.StatusRow
            For Each Str As String In My.Settings.Status.Split(";")
                If Str.Trim.Length > 0 Then
                    drStatus = lActions.Status.NewStatusRow
                    drStatus.Status = Str
                    lActions.Status.AddStatusRow(drStatus)
                End If
            Next

            Dim drCat As dsActionItem.CatagoriesRow
            For Each Str As String In My.Settings.Catagories.Split(";")
                If Str.Trim.Length > 0 Then
                    drCat = lActions.Catagories.NewCatagoriesRow
                    drCat.Catagory = Str
                    lActions.Catagories.AddCatagoriesRow(drCat)
                End If
            Next

            Dim drPerson As dsActionItem.PersonsRow
            For Each Str As String In My.Settings.Persons.Split(";")
                If Str.Trim.Length > 0 Then
                    drPerson = lActions.Persons.NewPersonsRow
                    drPerson.Name = Str
                    lActions.Persons.AddPersonsRow(drPerson)
                End If
            Next
            Catagories.Refresh()
            PersonAction.Refresh()

            SaveData()
        Catch ex As Exception
            BasicError(ex)
        End Try
    End Sub

#Region "temp Functions for testing "
    Sub FillDataSet()

        CreateNewFile()
        Dim dr As dsActionItem.ActionItemsRow = lActions.ActionItems.NewActionItemsRow
        dr.Description = "Description 1"
        dr.StartDate = Date.Now
        dr.ActionDate = Date.Now
        lActions.ActionItems.AddActionItemsRow(dr)

        dr = lActions.ActionItems.NewActionItemsRow
        dr.Description = "Description 2"
        dr.StartDate = Date.Now
        dr.ActionDate = Date.Now
        lActions.ActionItems.AddActionItemsRow(dr)

    End Sub
#End Region

    Private Sub SaveToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SaveToolStripButton.Click
        Me.Validate()
        SaveData()
    End Sub

    Private Sub HelpToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles HelpToolStripButton.Click
        FillDataSet()
    End Sub

    Private Sub OpenToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenToolStripButton.Click
        LoadData()
        BindingData()
    End Sub

    Private Sub btnAddNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddNew.Click
        Try
            Me.Validate()
            Dim dr As dsActionItem.ActionItemsRow = lActions.ActionItems.NewActionItemsRow
            dr.Description = ""
            dr.ActionDate = Date.Now
            dr.StartDate = Date.Now
            lActions.ActionItems.AddActionItemsRow(dr)

            lBindingSource.Position = lActions.ActionItems.Rows.IndexOf(dr)

            dgSummary.Refresh()
        Catch ex As Exception
            BasicError(ex)
        End Try

    End Sub

    Private Sub btnCatagory_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCatagory.Click

        If txtCatagory.Text.Length > 0 Then
            If txtCatagory.Tag.ToString.Length > 0 Then
                lActions.Catagories.DefaultView.RowFilter = "Catagory ='" & txtCatagory.Tag & "'"
                If lActions.Catagories.DefaultView.Count <> 0 Then
                    lActions.Catagories.DefaultView(0).Item("Catagory") = txtCatagory.Text
                End If
            Else
                lActions.Catagories.DefaultView.RowFilter = "Catagory ='" & txtCatagory.Text & "'"
                If lActions.Catagories.DefaultView.Count = 0 Then
                    Dim dr As dsActionItem.CatagoriesRow = lActions.Catagories.NewCatagoriesRow
                    dr.Catagory = txtCatagory.Text
                    lActions.Catagories.AddCatagoriesRow(dr)
                End If
            End If

        End If
        lActions.Catagories.DefaultView.RowFilter = ""
        txtCatagory.Tag = String.Empty
        txtCatagory.Text = String.Empty

    End Sub

    Private Sub btnPerson_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPerson.Click
        If txtPerson.Text.Length > 0 Then
            If txtPerson.Tag.ToString.Length > 0 Then
                lActions.Persons.DefaultView.RowFilter = "Name='" & txtPerson.Tag & "'"
                If lActions.Persons.DefaultView.Count <> 0 Then
                    lActions.Persons.DefaultView(0).Item("Name") = txtPerson.Text
                End If
            Else
                lActions.Persons.DefaultView.RowFilter = "Name='" & txtPerson.Text & "'"
                If lActions.Persons.DefaultView.Count = 0 Then
                    Dim dr As dsActionItem.PersonsRow = lActions.Persons.NewPersonsRow
                    dr.Name = txtPerson.Text
                    lActions.Persons.AddPersonsRow(dr)
                End If
            End If
        End If
        txtPerson.Text = String.Empty
        txtPerson.Tag = String.Empty
        lActions.Persons.DefaultView.RowFilter = ""
    End Sub

    Private Sub NewToolStripButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NewToolStripButton.Click
        Dim OpenFileDialog As New OpenFileDialog
        OpenFileDialog.InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        OpenFileDialog.Filter = "XML Files (*.txt)|*.txt|All Files (*.*)|*.*"

        If (OpenFileDialog.ShowDialog(Me) = System.Windows.Forms.DialogResult.OK) Then
            Dim FileName As String = OpenFileDialog.FileName
            ' TODO: Add code here to open the file.
        End If
    End Sub

    Private Sub Catagories_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles Catagories.MouseClick
        Debug.Print(lActions.Person_ActionItem.Rows.Count)
        Debug.Print(lActions.Catagory_ActionItem.Rows.Count)
        lBindingSource.EndEdit()
    End Sub

    Private Sub PersonAction_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles PersonAction.MouseClick
        lBindingSource.EndEdit()
    End Sub

    Private Sub txtDescription_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles txtDescription.LostFocus
        lBindingSource.EndEdit()
    End Sub

    Private Sub dgSummary_CellDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgSummary.CellDoubleClick
        Dim dgCell As DataGridViewCell = dgSummary.SelectedCells(0)
        Dim dgRow As DataGridViewRow = dgSummary.Rows(dgCell.RowIndex)
        pnlZoom.Visible = True
        pnlZoom.Left = 0
        pnlZoom.Top = 10
        pnlZoom.Width = Me.Width
        pnlZoom.Height = 500
        pnlZoom.BringToFront()

    End Sub

    Private Sub dgSummary_CellValidated(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgSummary.CellValidated
        lBindingSource.EndEdit()
    End Sub


    Private Sub mnuDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub mnuEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        txtCatagory.Tag = Catagories.SelectedItem.ToString
        txtCatagory.Text = Catagories.SelectedItem.ToString
    End Sub

    Private Sub mnuDeletePerson_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

    End Sub

    Private Sub mnuEditPerson_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        txtPerson.Tag = PersonAction.SelectedItem.ToString
        txtPerson.Text = PersonAction.SelectedItem.ToString
    End Sub
#Region "Grid Filter"

    Private Sub mnuClearFilter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuClearFilter.Click
        lActions.ActionItems.DefaultView.RowFilter = String.Empty
        strRowFilter = String.Empty
        For Each col As DataGridViewColumn In dgSummary.Columns
            col.HeaderText = col.HeaderText.ToString.Replace("*", "")
        Next

    End Sub

    Private Sub mnuFilterBy_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuFilterBy.Click
        Dim dgCell As DataGridViewCell = dgSummary.SelectedCells(0)
        Dim dgColum As DataGridViewColumn = dgSummary.Columns(dgCell.ColumnIndex)
        'Dim lRowFilter As String = lActions.ActionItems.DefaultView.RowFilter

        strRowFilter = String.Empty

        If Not dgColum.HeaderText.ToString.Contains("*") Then
            dgColum.HeaderText = dgColum.HeaderText & "*"
        End If

        If strRowFilter.Length > 0 Then
            strRowFilter &= " AND "
        End If

        strRowFilter &= " " & dgColum.DataPropertyName & " = "
        Select Case lActions.ActionItems.Columns(dgColum.DataPropertyName).DataType.ToString
            Case "System.Boolean", "System.Char", "System.String"
                strRowFilter &= " '" & dgCell.Value & "' "
            Case "System.DateTime"
                strRowFilter &= "#" & dgCell.Value.Month & "/" & dgCell.Value.Day & "/" & dgCell.Value.Year & "#"
        End Select

        lActions.ActionItems.DefaultView.RowFilter = strRowFilter '& CatagoryFilter() & PersonFilter()

        For Each col As DataGridViewColumn In dgSummary.Columns
            If strRowFilter.Contains(col.DataPropertyName) Then
            Else
                col.HeaderText = col.HeaderText.ToString.Replace("*", "")
            End If
        Next

    End Sub

    Private Sub mnuExclude_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles mnuExclude.Click
        Dim dgCell As DataGridViewCell = dgSummary.SelectedCells(0)
        Dim dgColum As DataGridViewColumn = dgSummary.Columns(dgCell.ColumnIndex)
        Dim lRowFilter As String = lActions.ActionItems.DefaultView.RowFilter

        If Not dgColum.HeaderText.ToString.Contains("*") Then
            dgColum.HeaderText = dgColum.HeaderText & "*"
        End If

        If lRowFilter.Length > 0 Then
            lRowFilter &= " AND "
        End If

        lRowFilter &= " " & dgColum.DataPropertyName & " <> "
        Select Case lActions.ActionItems.Columns(dgColum.DataPropertyName).DataType.ToString
            Case "System.Boolean", "System.Char", "System.String"
                lRowFilter &= " '" & dgCell.Value & "' "
            Case "System.DateTime"
                lRowFilter &= "#" & dgCell.Value.Month & "/" & dgCell.Value.Day & "/" & dgCell.Value.Year & "#"
        End Select

        lActions.ActionItems.DefaultView.RowFilter = lRowFilter

        For Each col As DataGridViewColumn In dgSummary.Columns
            If lRowFilter.Contains(col.DataPropertyName) Then
            Else
                col.HeaderText = col.HeaderText.ToString.Replace("*", "")
            End If
        Next

    End Sub
#End Region

    Private Sub dgSummary_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles dgSummary.CellContentClick

    End Sub

    Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnClose.Click
        Me.Validate()
        pnlZoom.Visible = False
    End Sub

    Private Sub lBindingSource_PositionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lBindingSource.PositionChanged
        Debug.Print(lBindingSource.Position)
    End Sub

    Private Sub FilterAdvanceToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FilterAdvanceToolStripMenuItem.Click
        pnlFilter.Visible = True
        pnlFilter.Left = 0
        pnlFilter.Top = 10
        pnlFilter.Width = Me.Width
        pnlFilter.Height = 500
        pnlFilter.BringToFront()
    End Sub

    Private Sub btnFilClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFilClose.Click
        Me.Validate()
        pnlFilter.Visible = False
    End Sub

    Function CatagoryFilter() As String
        Dim strCatagoryFilter As String = String.Empty
        Dim ActionsFilter As String = String.Empty
        For Each drCat As DataRowView In filtCatagories.SelectedItems
            strCatagoryFilter &= " CatagoryID =" & drCat.Item("CatagoryID") & " OR "
        Next
        If strCatagoryFilter.Length > 0 Then
            strCatagoryFilter = strCatagoryFilter.Substring(0, strCatagoryFilter.Length - 3)
        End If

        lActions.Catagory_ActionItem.DefaultView.RowFilter = strCatagoryFilter
        For iRow As Int32 = 0 To lActions.Catagory_ActionItem.DefaultView.Count - 1
            Dim strItemID As String = lActions.Catagory_ActionItem.DefaultView(iRow).Item("ItemID")
            If Not ActionsFilter.Contains("=" & strItemID & " ") Then
                ActionsFilter &= " ItemID =" & strItemID & " OR "
            End If
        Next
        If ActionsFilter.Length > 0 Then
            ActionsFilter = " ( " & ActionsFilter.Substring(0, ActionsFilter.Length - 3) & " ) "
        End If

        lActions.Catagory_ActionItem.DefaultView.RowFilter = String.Empty

        Return ActionsFilter
    End Function

    Function PersonFilter() As String
        Dim strPersonFilter As String = String.Empty
        Dim ActionsFilter As String = String.Empty
        For Each drCat As DataRowView In filtPeople.SelectedItems
            strPersonFilter &= " PersonID =" & drCat.Item("PersonID") & " OR "
        Next
        If strPersonFilter.Length > 0 Then
            strPersonFilter = strPersonFilter.Substring(0, strPersonFilter.Length - 3)
        End If

        lActions.Person_ActionItem.DefaultView.RowFilter = strPersonFilter
        For iRow As Int32 = 0 To lActions.Person_ActionItem.DefaultView.Count - 1
            Dim strItemID As String = lActions.Person_ActionItem.DefaultView(iRow).Item("ItemID")
            If Not ActionsFilter.Contains("=" & strItemID & " ") Then
                ActionsFilter &= " ItemID =" & strItemID & " OR "
            End If
        Next
        If ActionsFilter.Length > 0 Then
            ActionsFilter = " ( " & ActionsFilter.Substring(0, ActionsFilter.Length - 3) & " ) "
        End If

        lActions.Person_ActionItem.DefaultView.RowFilter = String.Empty

        Return ActionsFilter
    End Function

    Private Sub btnApply_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnApply.Click

        If strRowFilter.Length > 0 Then
            lActions.ActionItems.DefaultView.RowFilter = " ( " & strRowFilter & " ) "
        Else
            lActions.ActionItems.DefaultView.RowFilter = String.Empty
        End If

        If lActions.ActionItems.DefaultView.RowFilter.Length > 0 Then
            lActions.ActionItems.DefaultView.RowFilter &= " AND " & CatagoryFilter()
        Else
            lActions.ActionItems.DefaultView.RowFilter = CatagoryFilter()
        End If

        If lActions.ActionItems.DefaultView.RowFilter.Length > 0 Then
            lActions.ActionItems.DefaultView.RowFilter &= " AND " & PersonFilter()
        Else
            lActions.ActionItems.DefaultView.RowFilter = PersonFilter()
        End If
        'lActions.ActionItems.DefaultView.RowFilter &= CatagoryFilter() & PersonFilter()

        Me.Validate()
        pnlFilter.Visible = False
    End Sub

End Class